/*
 * Copyright (c) 2020 Tenny
 *  typescript-init is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *           http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */
const Prompt = require('./prompt');
const readline = require('readline');
const colors = require('terminal-simple-colors');

class ConfirmPrompt extends Prompt {
  constructor (rl, question, event) {
    super(rl, question, event);
    this.default();
    this.render();
  }

  default () {
    let sd = this.question.default;
    let d = false;
    if (sd != null) {
      if (typeof sd === 'boolean') {
        d = sd;
      } else if (typeof sd === 'string') {
        sd = sd.toLowerCase();
        if (sd === 'yes' || sd === 'y') {
          d = true;
        }
      }
    }
    this._default = d;
  }

  getValue (v) {
    v = v.trim().toLowerCase();
    if (v.length === 0) {
      return this._default;
    } else if (v === 'y' || v === 'yes') {
      return true;
    }
    return false;
  }

  render () {
    let qt = this.question.message + ' (Y/N) ';
    if (this.question.default != null) {
      qt += ' default: ' + this._default + ' ';
    }
    this.rl.question(qt, (answer) => {
      // 移动到开始位置
      readline.moveCursor(process.stdout, 0, -1);
      readline.clearLine(process.stdout, 0); // 清除当前行数据
      let value = this.getValue(answer);
      this.rl.write(this.question.message + ' ' + colors.green(value ? 'Yes' : 'No') + '\r\n'); // 重新写数据
      readline.moveCursor(process.stdout, 0, 0);
      this.event(this.question.name, value);
    })
  }
}

module.exports = ConfirmPrompt;